//
//  WBStatusListViewModel.swift
//  新浪微博
//
//  Created by zj on 2017/10/15.
//  Copyright © 2017年 zj. All rights reserved.
//

import Foundation

/// 微博数据列表视图模型

private let maxPullupTryTimes = 3

class WBStatusListViewModel {
    
    lazy var statusList = [WBStatus]()
    private var pullupErrorTimes = 0
    
    func loadStatus(pullup: Bool, completion: @escaping (_ isSuccess: Bool, _ shouldRefresh: Bool)->()) {
        
        if pullup && pullupErrorTimes > maxPullupTryTimes {
            completion(true, false)
            
            return
        }
        
        // since_id 下拉刷新
        let since_id = pullup ? 0 : (statusList.first?.id ?? 0)
        // 上拉刷新
        let max_id = !pullup ? 0 : (statusList.last?.id ?? 0)
        
        WBNetworkManager.shared.statusList(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            guard let array = NSArray.yy_modelArray(with: WBStatus.self, json: list ?? []) as? [WBStatus] else {
                completion(isSuccess, false)
                return
            }
            
            print("刷新到 \(array.count) 条数据")
            // FIXME:
            // 下拉刷新，应该将结果
            if pullup {
                self.statusList += array
            } else {
                self.statusList = array + self.statusList
            }
            
            if pullup && array.count == 0 {
                self.pullupErrorTimes += 1
                completion(isSuccess, false)
            } else {
                completion(isSuccess, true)
            }
        }
    }
}
